const connection = require('@/app/database')

class UserService {
  async create(user) {
    const { account, password } = user
    const statement = `INSERT INTO sys_user (account, password) VALUES (?, ?);`
    const result = await connection.execute(statement, [account, password])
    return result[0]
  }

  async getUserByAccount(account) {
    const statement = `SELECT * FROM sys_user WHERE account = ?;`
    const [result] = await connection.execute(statement, [account])
    return result
  }

  async getUserInfo(id) {
    const statement = `
      SELECT su.id, su.account, su.nickName, su.avatar, su.sex, su.remark, su.wechat, su.occupation
      FROM sys_user su
      WHERE id = ?;
    `
    const [result] = await connection.execute(statement, [id])
    return result[0]
  }

  async queryMenuList(id) {
    if (id == 1) {
      const statement = `SELECT * FROM sys_menu ORDER BY orderNum, id;`
      const result = await connection.execute(statement)
      return result[0]
    } else {
      const statement = `
      SELECT sm.*
      FROM sys_user su
      JOIN sys_role sr ON su.id = sr.id
      JOIN sys_role_menu srm ON sr.id = srm.roleId
      JOIN sys_menu sm ON srm.menuId = sm.id
      WHERE su.id = ? AND sm.status = 0
      ORDER BY orderNum, id;
    `
      const result = await connection.execute(statement, [id])
      return result[0]
    }
  }
}

module.exports = new UserService()
